package com.yunji.common.event;

import com.yunji.common.event.entity.EventData;
import com.yunji.common.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * @author : peter-zhu
 * @date : 2025/3/17 16:01
 * @description : TODO
 **/
@Service
public class SpringEventBus implements EventBus {

    private static SpringEventBus instance;

    private final ApplicationEventPublisher publisher;

    @Autowired
    public SpringEventBus(ApplicationEventPublisher applicationEventPublisher) {
        this.publisher = applicationEventPublisher;
        instance = this;
    }

    public static SpringEventBus getInstance() {
        if (instance == null) {
            throw new ServiceException("SpringEventBus 还未初始化，无法获取实例！");
        }
        return instance;
    }

    @Async
    @Override
    public <T> void publishAsync(EventData<T> event) {
        publisher.publishEvent(event);
    }

    @Override
    public <T> void publish(EventData<T> event) {
        publisher.publishEvent(event.getEventData());
    }
}
